import java.util.Deque;
import java.util.LinkedList;

/**
 * @author 雷明浩
 * @date 2025/5/29 16:23
 */
public class IsSymmetric {
    // leetcode 对称二叉树
    // https://leetcode.cn/problems/symmetric-tree/?envType=study-plan-v2&envId=top-100-liked
    public boolean isSymmetric1(TreeNode root) {
        return isSymmetricChild(root.left, root.right);
    }

    private boolean isSymmetricChild(TreeNode left, TreeNode right) {
        if (left == null && right == null) {
            return true;
        }else if (left == null && right != null || left != null && right == null) {
            return false;
        }
        if (left.val != right.val) {
            return false;
        }
        boolean leftResult = isSymmetricChild(left.left, right.right);
        if (!leftResult) {
            return false;
        }
        return isSymmetricChild(left.right, right.left);
    }

    /**
     * 非递归实现
     * @param root
     * @return
     */
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        Deque<TreeNode> deque = new LinkedList<>();
        deque.add(root.left);
        deque.add(root.right);
        while (!deque.isEmpty()) {
            TreeNode leftNode = deque.poll();
            TreeNode rightNode = deque.poll();
            if (leftNode == null && rightNode == null) {
                continue;
            }
            if (leftNode == null || rightNode == null || leftNode.val != rightNode.val) {
                return false;
            }
            deque.add(leftNode.left);
            deque.add(rightNode.right);
            deque.add(leftNode.right);
            deque.add(rightNode.left);
        }
        return true;
    }
}